package com.example.coffee.slice;

import com.example.coffee.ResourceTable;
import com.example.coffee.items.StoreItem;
import com.example.coffee.mock.DataMockManager;
import com.example.coffee.provider.StoreListDataProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;

import java.util.List;

public class StoreSlice extends AbilitySlice {
    // 列表组件，数据源与Provider
    private ListContainer storeList = null;
    private List<StoreItem> storeListData = null;
    private StoreListDataProvider storeListProvider = null;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        // 加载布局文件
        super.setUIContent(ResourceTable.Layout_store_slice);
        // 初始化工作
        setup();
    }

    private void setup() {
        // 组件与数据源的初始化
        storeList = (ListContainer) findComponentById(ResourceTable.Id_store_list);
        storeListData = DataMockManager.mockStoreList();
        storeListProvider = new StoreListDataProvider(storeListData, this);
        storeList.setItemProvider(storeListProvider);
        storeList.setBindStateChangedListener(new Component.BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                storeListProvider.notifyDataChanged();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
            }
        });
        // 列表项的点击事件
        storeList.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                // 传值到页面的调起方
                Intent intent = new Intent();
                // 将地址与距离数据进行传递
                intent.setParam("distance", storeListData.get(i).getDistance());
                intent.setParam("address", storeListData.get(i).getAddress());
                // 反向传值
                setResult(intent);
                // 关闭当前页面
                terminate();
            }
        });
    }
}
